package com.rh.soc.equipmenttypethirdinterface.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.rh.soc.equipmentclassthirdinterface.dao.IEquipmentClassThirdDAO;
import com.rh.soc.equipmenttypethirdinterface.dao.IEquipmentTypeThirdDAO;
import com.rh.soc.equipmenttypethirdinterface.service.IEquipmentTypeThirdService;
import com.rh.soc.management.basedata.equipmenttype.model.EquipmentClassVO;
import com.rh.soc.management.basedata.equipmenttype.model.EquipmentTypeVO;
import com.rh.soc.management.basedata.equipmenttype.service.impl.EquipmentTypeServiceImpl;
import com.rh.webserver.common.base.cache.CodeList;
import com.rh.webserver.common.base.cache.CodeListEnable;
import com.rh.webserver.common.base.exception.AppException;
import com.rh.webserver.common.base.service.BaseService;
import com.rh.webserver.common.util.PropUtil;
import com.rh.webserver.common.util.StringUtil;

import sun.misc.BASE64Decoder;

@CodeListEnable
@Service
@Transactional
public class EquipmentTypeThirdServiceImpl extends BaseService implements IEquipmentTypeThirdService {
	private static final Logger logger = Logger.getLogger(EquipmentTypeServiceImpl.class);

	@Resource
	private IEquipmentTypeThirdDAO equipmentTypeThirdDAO;
	
	@Resource
	private IEquipmentClassThirdDAO equipmentClassThirdDAO;

	/**
	 * 添加页面保存数据}
	 */
	public int addEquipmentTypeSave(HttpServletRequest request,EquipmentTypeVO vo) throws AppException {
		try {
			int rtn = 0;
			
			String filePath = getUploadPath(request);
			String fileName="unknow.png";
			if(StringUtil.isNotEmpty(vo.getDeviceTypeMapContent())){
				fileName = getNewName(vo.getDeviceTypeMap()); // 图片名称
			}
			/**
			 * 判断资产大类是否存在
			 */
			EquipmentClassVO pidVo = new EquipmentClassVO();
			pidVo.setDeviceClass(vo.getDeviceClass());
			pidVo.setCurrentPageNum(1);
			pidVo.setPageSize(10);
			List<EquipmentClassVO> pidIsExist = equipmentClassThirdDAO.queryEquipmentTypeDataById(pidVo);// 查询是否有重名类型
			
			
			/**
			 * 判断是否有重名
			 */
			EquipmentTypeVO nameVo = new EquipmentTypeVO();
			nameVo.setDeviceTypeName(vo.getDeviceTypeName());
			nameVo.setDeviceType(null);
			nameVo.setCurrentPageNum(1);
			nameVo.setPageSize(10);
			List<EquipmentTypeVO> nameUsed = equipmentTypeThirdDAO.queryEquipmentTypeData(nameVo);// 查询是否有重名类型

			EquipmentTypeVO typeVo = new EquipmentTypeVO();
			typeVo.setDeviceTypeName(null);
			typeVo.setDeviceType(vo.getDeviceType());
			typeVo.setCurrentPageNum(1);
			typeVo.setPageSize(10);
			List<EquipmentTypeVO> typeUserd = equipmentTypeThirdDAO.queryEquipmentTypeData(typeVo);// 查询是否有重名类型

			
			if (pidIsExist.size() == 0) {
				rtn = 9;
			}
			
			else if (nameUsed.size() != 0) {
				rtn = 2;
			}

			else if (typeUserd.size() != 0) {
				rtn = 3;
			}

			else {
				String dbpath = "/soc/Resources/equipmenttype/";
				String name = dbpath + fileName;
				vo.setDeviceTypeMap(name);
				rtn = equipmentTypeThirdDAO.addEquipmentTypeSave(vo);
//				handleAssetTypeVsOs(vo, false);
				try {
					if(StringUtil.isNotEmpty(vo.getDeviceTypeMapContent())){
						saveImage(vo.getDeviceTypeMapContent(), filePath + dbpath, fileName);
					}
				} catch (Exception ex) {
					logger.error("文件上传失败", ex);
					throw new AppException(ex);
				}
			}
			return rtn;
		} catch (Exception e) {
			logger.error("插入设备类型失败。", e);
			throw new AppException(e);
		}
	}
	
	
	/**
	 * 保存修改数据
	 * 
	 */
	public int updEquipmentTypeSave(HttpServletRequest request,EquipmentTypeVO vo)
			throws AppException {
		try {
			int rtn = 0;
			
			EquipmentClassVO pidVo = new EquipmentClassVO();
			pidVo.setDeviceClass(vo.getDeviceClass());
			pidVo.setCurrentPageNum(1);
			pidVo.setPageSize(10);
			List<EquipmentClassVO> pidIsExist = equipmentClassThirdDAO.queryEquipmentTypeDataById(pidVo);// 查询是否有重名类型
			
			
			EquipmentTypeVO nameVo = new EquipmentTypeVO();
			nameVo.setDeviceTypeName(vo.getDeviceTypeName());
			nameVo.setDeviceType(vo.getDeviceType());
			nameVo.setCurrentPageNum(1);
			nameVo.setPageSize(10);
			List<EquipmentTypeVO> nameUsed = equipmentTypeThirdDAO.queryEquipmentTypeDataUpdate(nameVo);// 查询是否有重名类型

			EquipmentTypeVO typeVo = new EquipmentTypeVO();
			typeVo.setDeviceTypeName(null);
			typeVo.setDeviceType(vo.getDeviceType());
			typeVo.setCurrentPageNum(1);
			typeVo.setPageSize(10);
			List<EquipmentTypeVO> typeUserd = equipmentTypeThirdDAO.queryEquipmentTypeData(typeVo);// 查询id是否存在
			
			//如果class不存在，则返回失败
			if (pidIsExist.size() == 0) {
				rtn = 9;
			}

			//如果type不存在，则返回失败
			else if (typeUserd.size() == 0) {
				rtn = 3;
			}
			
			else if (nameUsed.size() != 0) {
				rtn = 2;
			}
			else{
				
				String oldDeviceTypeMap=null;
				String filePath = getUploadPath(request);
				String dbpath = "/soc/Resources/equipmenttype/";
				
				if (null != typeUserd && typeUserd.size() > 0) {
					oldDeviceTypeMap = typeUserd.get(0).getDeviceTypeMap();
				}
				
				String fileName = "";
				String deviceClassMap = "";
				
				if (StringUtils.isNotEmpty(vo.getDeviceTypeMapContent())) {
					fileName = getNewName(vo.getDeviceTypeMap());
					deviceClassMap = dbpath + fileName;
				} else if (StringUtils.isEmpty(vo.getDeviceTypeMapContent()) && StringUtils.isEmpty(oldDeviceTypeMap)) {
					fileName = "unknow.png";
					deviceClassMap = dbpath + fileName;
				} else if (StringUtils.isEmpty(vo.getDeviceTypeMapContent()) && StringUtils.isNotEmpty(oldDeviceTypeMap)) {
					deviceClassMap = oldDeviceTypeMap;
				}
				vo.setDeviceTypeMap(deviceClassMap);
				rtn = equipmentTypeThirdDAO.updEquipmentTypeSave(vo);
//				handleAssetTypeVsOs(vo, false);
				try {
					if(StringUtil.isNotEmpty(vo.getDeviceTypeMapContent())){
						saveImage(vo.getDeviceTypeMapContent(), filePath + dbpath, fileName);
					}
				} catch (Exception ex) {
					logger.error("文件上传失败", ex);
					throw new AppException(ex);
				}
				
			}

			return rtn;
		} catch (Exception e) {
			logger.error("修改设备类型失败。", e);
			throw new AppException(e);
		}
	}


	/**
	 * 删除选择数据
	 * 
	 */
	// public int delEquipmentType(EquipmentTypeVO vo, HttpServletRequest
	// request) throws AppException
	// {
	// try {
	// int rtn = 0;
	// String deviceType = vo.getDeviceType();
	// SqlRowSet typeUsed = this.queryDataFromEntityDevice(deviceType);//
	// 查询类型是否被实体使用
	// if (!typeUsed.next()) {
	// String filePath = this.getImagePath(request, vo);// 获取将要删除的设备类型的图片的绝对地址
	// rtn = equipmentTypeThirdDAO.delEquipmentType(vo);
	// if (0 < rtn) {
	// File image = new File(filePath);// 在删除设备类型成功之后在服务器删除其原图片
	// image.delete();
	// }
	// }
	//
	// else {
	// rtn = -2;
	// }
	// return rtn;
	// }
	// catch (Exception e) {
	// logger.error("删除设备类型失败。", e);
	// throw new AppException(e);
	// }
	// }

	/**
	 * 页面初始，查询所有数据；修改时根据id查询单一数据
	 * 
	 */
	public List<EquipmentTypeVO> queryEquipmentTypeData(EquipmentTypeVO vo) throws AppException {
		try {
			return equipmentTypeThirdDAO.queryEquipmentTypeData(vo);
		} catch (Exception e) {
			logger.error("获取数据失败。", e);
			throw new AppException(e);
		}

	}

	/**
	 * 查询总类型数据
	 * 
	 */
	public Map<String, List<EquipmentClassVO>> queryClassType(EquipmentClassVO vo) throws AppException {
		try {
			Map<String, List<EquipmentClassVO>> map = new HashMap<String, List<EquipmentClassVO>>();
			List<EquipmentClassVO> osList = equipmentTypeThirdDAO.queryOsType(vo);
			List<EquipmentClassVO> deviceList = equipmentTypeThirdDAO.queryClassType(vo);
			map.put("os", osList);
			map.put("device", deviceList);

			return map;
		} catch (Exception e) {
			logger.error("获取数据失败。", e);
			throw new AppException(e);
		}

	}

	
	/**
	 * 查询实体设备表，确认类型是否被使用
	 * 
	 */
	private SqlRowSet queryDataFromEntityDevice(long deviceClass) throws AppException {
		SqlRowSet result = equipmentTypeThirdDAO.queryDataFromEntityDevice(deviceClass);
		return result;
	}

	/**
	 * 获取新的上传文件的名称
	 * 
	 */
	private String getNewName(String deviceTypeMapName) {
		if (null == deviceTypeMapName) {
			return null;
		}
		// IFile file = upload.getFiles().getFile(0);
		String name = deviceTypeMapName;// 得到上传文件的原名称
		if (name.lastIndexOf(".") == -1) {
			return "";
		}
		name = "equipmenttype" + name.substring(name.lastIndexOf("."), name.length());
		if (name != null && StringUtils.isNotEmpty(name)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssS");// 格式化时间输出
			String Rname = sdf.format(new Date());// 取得当前时间，Date()是java.util包里的，这作为真实名称
			int i = name.lastIndexOf(".");// 原名称里倒数第一个"."在哪里
			String ext = name.substring(i + 1);// 取得后缀，即"."后面的字符
			String fore = name.substring(0, i);// 取得前缀，即"."前面的字符
			name = fore + Rname + "." + ext;// 拼凑而成
			// file.setFileName(name);// 将保存文件名修改为拼上了时间的文件名
		}
		return name;
	}

	/**
	 * 获取上传文件的保存路径
	 * 
	 */
	private String getUploadPath(HttpServletRequest request) {
		String uploadPath = request.getSession().getServletContext().getRealPath("")
				+ PropUtil.getAppProp("ostype_image_path");
		File file = new File(uploadPath);
		if (!file.exists()) {
			file.mkdir();
		}
		return uploadPath;
	}

	/**
	 * 获取某设备类型的图片磁盘绝对地址
	 * 
	 */
	String getImagePath(HttpServletRequest request, EquipmentTypeVO vo) throws AppException {
		String filepath = "";
		EquipmentTypeVO tempVo = new EquipmentTypeVO();
		// tempVo.setDeviceType(vo.getDeviceType());
		tempVo.setOldDeviceType(vo.getOldDeviceType());
		tempVo.setCurrentPageNum(1);
		tempVo.setPageSize(10);
		List<EquipmentTypeVO> result = equipmentTypeThirdDAO.queryEquipmentTypeData(tempVo);
		EquipmentTypeVO changVo = (EquipmentTypeVO) result.iterator().next();// 查数据库获取指定id的设备类型
		String filename = changVo.getDeviceTypeMap();// 获得类型的图片相对地址
		// filename = filename.replace("/", "\\");//将工程地址转变为Windows地址
		String contextPath = request.getSession().getServletContext().getRealPath("");
		filepath = contextPath + filename;
		return filepath;
	}

	/**
	 * 
	 * 批量删除
	 * 
	 */
	@Override
	public int delBatch(List<EquipmentTypeVO> list, HttpServletRequest request) throws AppException {
		try {
			for (EquipmentTypeVO voi : list) {
				equipmentTypeThirdDAO.updAssetType(voi);
				// String filePath = this.getImagePath(request, voi);//
				// 获取将要删除的设备类型的图片的绝对地址
				equipmentTypeThirdDAO.delEquipmentType(voi);
				// if (0 < rtn) {
				// File image = new File(filePath);// 在删除设备类型成功之后在服务器删除其原图片
				// image.delete();
				// }
			}
			return 1;
		} catch (Exception e) {
			logger.error("批量删除失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 
	 * 批量删除前查询是否可以删除
	 * 
	 */
	@Override
	public List<EquipmentTypeVO> preBatchDel(List<EquipmentTypeVO> list) throws AppException {
		try {
			List<EquipmentTypeVO> retList = new ArrayList<EquipmentTypeVO>();
			for (EquipmentTypeVO voi : list) {
				if (queryDataFromEntityDevice(Long.parseLong(voi.getDeviceType())).next()) {
					retList.add(voi);
				}
			}
			return retList;
		} catch (Exception e) {
			logger.error("批量删除前查询失败", e);
			throw new AppException(e);
		}
	}

	/**
	 * 
	 * {删除前查询是否可以删除}
	 * 
	 */
	// public List<EquipmentTypeVO> doPreBatchDel(List<EquipmentTypeVO> list)
	// throws AppException
	// {
	// try {
	// List<EquipmentTypeVO> retList = new ArrayList<EquipmentTypeVO>();
	// for (EquipmentTypeVO voi : list) {
	// if (queryDataFromEntityDevice(voi.getDeviceType()).next()) {
	// retList.add(voi);
	// }
	// }
	// return retList;
	// }
	// catch (Exception e) {
	// logger.error("删除前查询失败", e);
	// throw new AppException(e);
	// }
	// }

	/**
	 * 
	 * {处理资产类型与操作系统关联关系}
	 * 
	 */
	private void handleAssetTypeVsOs(EquipmentTypeVO vo, boolean handleFlag) {
		if (handleFlag) {
			equipmentTypeThirdDAO.delAssetTypeVsOs(String.valueOf(vo.getDeviceType()));
		}
		if (StringUtils.isNotEmpty(vo.getOsType())) {
			for (String osType : vo.getOsType().split(",")) {
				equipmentTypeThirdDAO.addAssetTypeVsOs(String.valueOf(vo.getDeviceType()), osType);
			}
		} else {
			// 当页面为选择关联操作系统类别时，默认添加未定义操作系统类别（108）
			equipmentTypeThirdDAO.addAssetTypeVsOs(String.valueOf(vo.getDeviceType()), "108");
		}
	}

	/**
	 * 
	 * {同步资产类型}
	 * 
	 */
	// public void syncEquipmentType() throws AppException {
	// try {
	// EquipmentClassVO classVo = new EquipmentClassVO();
	// classVo.setPageSize(9999999);
	// classVo.setCurrentPageNum(1);
	// List<EquipmentClassVO> deviceClassList =
	// equipmentTypeThirdDAO.queryClassType(classVo);
	//
	// EquipmentTypeVO typeVo = new EquipmentTypeVO();
	// typeVo.setPageSize(9999999);
	// typeVo.setCurrentPageNum(1);
	// List<EquipmentTypeVO> deviceTypeList =
	// equipmentTypeThirdDAO.queryEquipmentTypeData(typeVo);
	//
	// String result = EquipmentTypeXml(deviceClassList, deviceTypeList);
	// ITSMClient.doITSMService("asset_type_sync", result);
	// }catch (Exception e) {
	// logger.error("同步资产类型失败", e);
	// throw new AppException(e);
	// }
	// }

	/**
	 * 
	 * {创建xml结构}
	 * 
	 */
	// private String EquipmentTypeXml(List<EquipmentClassVO> deviceClassList,
	// List<EquipmentTypeVO> deviceTypeList) {
	// Document document = org.dom4j.DocumentHelper.createDocument();
	// document.setXMLEncoding("gbk");
	// Element root = document.addElement("root");
	// for (EquipmentClassVO vo : deviceClassList) {
	// Element deviceClass = root.addElement("deviceClass");
	// deviceClass.addElement("deviceClassId").setText(vo.getDeviceClass() == 0
	// ? "" : String.valueOf(vo.getDeviceClass()));// 资产类型大类ID
	// deviceClass.addElement("deviceClassName").setText(StringUtils.isEmpty(vo.getDeviceClassName())
	// ? "" : vo.getDeviceClassName());// 资产类型大类名称
	// deviceClass.addElement("deviceClassSort").setText(StringUtils.isEmpty(vo.getDeviceClassSort())
	// ? "" : vo.getDeviceClassSort());// 资产类型大类权重
	// }
	// for (EquipmentTypeVO vo : deviceTypeList) {
	// Element deviceType = root.addElement("deviceType");
	// deviceType.addElement("deviceTypeId").setText(vo.getDeviceType());//
	// 资产类型小类ID
	// deviceType.addElement("deviceClassId").setText(vo.getDeviceClass() == 0 ?
	// "" : String.valueOf(vo.getDeviceClass()));// 资产类型大类ID
	// deviceType.addElement("deviceTypeName").setText(StringUtils.isEmpty(vo.getDeviceTypeName())
	// ? "" : vo.getDeviceTypeName());// 资产类型小类名称
	// deviceType.addElement("deviceTypeSort").setText(vo.getDeviceTypeSort() ==
	// 0 ? "" : String.valueOf(vo.getDeviceTypeSort()));// 资产类型小类权重
	// }
	// return document.asXML();
	// }

	/**
	 * 查询资产类型（华能定制）
	 * 
	 */
	// public String queryAssetTypeForHuaneng() throws AppException
	// {
	// EquipmentTypeVO vo = new EquipmentTypeVO();
	// vo.setCurrentPageNum(1);
	// vo.setPageSize(10000);
	// List<EquipmentTypeVO> list =
	// equipmentTypeThirdDAO.queryEquipmentTypeData(vo);
	// Document d = DocumentHelper.createDocument();
	// d.setXMLEncoding("gbk");
	// Element deviceTypeRoot = d.addElement("root");
	// Element equipmentTypes = deviceTypeRoot.addElement("equipmentTypes");
	// for (EquipmentTypeVO equipmentTypeVO : list) {
	// Element equipmentType = equipmentTypes.addElement("equipmentType");
	// equipmentType.addElement("deviceType").setText(equipmentTypeVO.getDeviceType()+"");
	// equipmentType.addElement("deviceClass").setText(equipmentTypeVO.getDeviceClass()+"");
	// equipmentType.addElement("deviceTypeName").setText(equipmentTypeVO.getDeviceTypeName()==null?"":equipmentTypeVO.getDeviceTypeName());
	// equipmentType.addElement("deviceClassName").setText(equipmentTypeVO.getDeviceClassName()==null?"":equipmentTypeVO.getDeviceClassName());
	// equipmentType.addElement("osName").setText(equipmentTypeVO.getOsName()==null?"":equipmentTypeVO.getOsName());
	// equipmentType.addElement("deviceTypeMap").setText(equipmentTypeVO.getDeviceTypeMap()==null?"":equipmentTypeVO.getDeviceTypeMap());
	// }
	// return d.asXML();
	//
	// }
//	private void saveImage(EquipmentTypeVO vo, String prePath, String filename) {
//		try {
//			// 未完成，调试再弄
//			String savePath = prePath + filename;
//			File preDir = new File(prePath);
//			if (!preDir.exists()) {
//				preDir.mkdirs();
//			}
//			uploadFile.transferTo(new File(savePath));
//		} catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}
//	}
	
	
	 public static void saveImage(String base64, String path,  
	            String imgName) {  
		 	 
		 	base64 = base64.substring(base64.indexOf("base64,")+7);
		 	base64=base64.replaceAll(" ", "+");
		 	logger.info("base64:"+base64);
			BASE64Decoder decoder = new BASE64Decoder();
	        FileOutputStream write=null;
	        try {  
	        	
	        	File preDir = new File(path);
				if (!preDir.exists()) {
					preDir.mkdirs();
				}
				
	            write = new FileOutputStream(new File(path + imgName));  
	            byte[] decoderBytes = decoder.decodeBuffer(base64);  
	            write.write(decoderBytes);  
	            write.flush();
	            write.close();  
	        } catch (IOException e) {  
	            e.printStackTrace();  
	        } 
	        finally{
	        	try {
					if (write != null) {
						write.close();
					} 
				} catch (Exception e2) {
					e2.printStackTrace();
				}
	        }
	    }  

	@CodeList("equipmentClasslist")
	@Override
	public List<EquipmentClassVO> queryEquipmentClass(EquipmentClassVO vo) throws AppException {
		try {
			List<EquipmentClassVO> deviceList = equipmentTypeThirdDAO.queryClassType(vo);
			return deviceList;
		} catch (Exception e) {
			logger.error("获取数据失败。", e);
			throw new AppException(e);
		}

	}
	
}
